package com.gqz.patrol.app.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import org.apache.commons.lang3.StringUtils;

import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;

/**
 * @Author: gqz1
 * @CreateTime: 2022-11-25  12:29
 */
public class QueryParamTool {
    /**
     * 生成查询所需的map
     *
     * @param entityClazz
     * @param entity
     * @return hashmap
     */
    public static <T> HashMap<SFunction<T, ?>, Object> getsFunctionObjectMap(Class<?> entityClazz, T entity) {
        HashMap<SFunction<T, ?>, Object> map = new HashMap<>();
        PropertyDescriptor[] origDescriptors = BeanUtil.getPropertyDescriptors(entityClazz);
        final Method genColumnSFunction;
        try {
            //必须保证有这个方法
            genColumnSFunction = entityClazz.getDeclaredMethod("genColumnSFunction", String.class);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }

        Arrays
                .stream(origDescriptors)
                .forEach(description -> {
                    try {
                        Class<?> fieldType = description.getPropertyType();
                        Method readMethod = description.getReadMethod();
                        readMethod.setAccessible(true);
                        Object o = readMethod.invoke(entity);
                        if (o == null ||
                                StringUtils.isBlank(o.toString()) ||
                                fieldType.getName().equals("java.util.Date")) {
                            return;
                        }
                        //获取字段名称,字段首字母一定小写
                        String field = description.getName();
                        String s = StrUtil.lowerFirst(field);
                        //获取entity中map字段
                        SFunction<T, ?> func = (SFunction<T, ?>) genColumnSFunction.invoke(entity, s);
                        if (func != null) {
                            map.put(func, o);
                        }
                    } catch (IllegalAccessException | InvocationTargetException e) {
                        throw new RuntimeException(e);
                    }
                });
        return map;
    }
}
